<template>
  <div class="role-list">
    <div class="title">角色权限</div>
    <div>
      <el-form v-if="rolesCode === 'ROLE_ADMIN'" :inline="true" class="search-form">
        <el-col :span="19">
          <el-form-item>
            <el-input v-model="searchName" placeholder="输入角色名称" clearable @keyup.enter.native="queryList('search')">
              <el-button class="search-icon" slot="append" icon="icon-sousuo" @click="queryList('search')"></el-button>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-button type="primary" class="button-container" size="14" @click="handleAdd">新增角色</el-button>
        </el-col>
      </el-form>
    </div>
    <el-table
      v-loading="loading"
      :data="tableData"
      style="width: 100%"
      size="medium"
      :header-cell-style="{ background: '#F5F6F7' }">
      <el-table-column label="角色">
        <template slot-scope="scope">
          {{ scope.row.roleName || "-" }}
        </template>
      </el-table-column>
      <el-table-column v-if="rolesCode === 'ROLE_ADMIN'" label="角色标识">
        <template slot-scope="scope">
          {{ scope.row.roleCode || "-" }}
        </template>
      </el-table-column>
      <el-table-column label="操作权限说明">
        <template slot-scope="scope">
          {{ scope.row.roleDesc || "-" }}
        </template>
      </el-table-column>
      <el-table-column
        v-if="rolesCode === 'ROLE_ADMIN' || rolesCode === 'PLATFORM_ADMIN'"
        fixed="right"
        label="菜单权限">
        <template slot-scope="scope">
          <el-button
            v-if="rolesCode === 'ROLE_ADMIN'"
            type="text"
            size="operate"
            @click="handleEdit(scope.row)">编辑</el-button>
          <el-button
            v-if="rolesCode === 'ROLE_ADMIN'"
            type="text"
            size="operate"
            @click="handleDelete(scope.row.roleId)">删除</el-button>
          <el-button type="text" size="operate" @click="handlePermission(scope.row, scope.index)">权限编辑
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-if="tableData.length > 10"
      :current-page="currentPage"
      :page-sizes="[10, 20, 50]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange">
    </el-pagination>

    <el-dialog
      :title="status === 'add' ? '新增角色' : '编辑角色'"
      :visible.sync="dialogVisible"
      width="628px"
      :before-close="handleClose">
      <el-form
        ref="form"
        class="define-form"
        :model="addFormData"
        :rules="rules"
        label-width="110px"
        label-position="right">
        <el-form-item label="角色" prop="roleName">
          <el-input v-model="addFormData.roleName" placeholder="请输入角色" clearable></el-input>
        </el-form-item>
        <el-form-item label="角色标识" prop="roleCode">
          <el-input v-model="addFormData.roleCode" placeholder="请输入角色标识" clearable></el-input>
        </el-form-item>
        <el-form-item label="操作权限说明" prop="roleDesc">
          <el-input v-model="addFormData.roleDesc" placeholder="请输入操作权限说明" clearable></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="14" @click="handleClose">取 消</el-button>
        <el-button type="primary" size="14" @click="onsubmit">确 定 </el-button>
      </span>
    </el-dialog>

    <el-dialog :visible.sync="dialogPermissionVisible" :close-on-click-modal="false" width="628px" title="分配权限" custom-class="menu-dialog">
      <div class="dialog-main-tree">
        <el-tree
          ref="menuTree"
          :data="treeData"
          :default-checked-keys="checkedKeys"
          :check-strictly="false"
          :props="defaultProps"
          :filter-node-method="filterNode"
          class="filter-tree"
          node-key="id"
          highlight-current
          show-checkbox
          default-expand-all />
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" @click="updatePermession(roleId)">更 新
        </el-button>
        <el-button type="default" size="small" @click="cancal()">取消
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addObj, delObj, fetchRoleTree, putObj, rolePage, permissionRoleMenu } from '@/api/admin/role'
import { fetchMenuTree } from '@/api/admin/menu'
import { mapGetters } from 'vuex'
export default {
  name: "Tenant",
  data() {
    return {
      searchName: "", // 产品id或名称
      tableData: [], // 列表数据
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页条数
      total: 0, // 列表数据总条数
      loading: true,
      dialogVisible: false,
      addFormData: {
        roleId: '',
        roleName: '',
        roleCode: '',
        roleDesc: ''
      },
      rules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        roleCode: [
          { required: true, message: '请输入角色标识', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入操作权限说明', trigger: 'blur' }
        ]

      },
      status: '',
      treeData: [],
      checkedKeys: [],
      defaultProps: {
        label: 'name',
        value: 'id'
      },
      roleManager_btn_perm: false,
      dialogPermissionVisible: false // 权限弹窗
    }
  },
  computed: {
    ...mapGetters(['permissions', 'rolesCode'])
  },
  created() {
    this.roleManager_btn_perm = this.permissions['sys_role_perm']
    this.queryList()
  },
  methods: {
    /**
     * 查询角色列表
     * current 当前页码
     * size 每页条数
     * name 角色名称
     */
    queryList(condition) {
      this.currentPage = condition === 'search' ? 1 : this.currentPage
      this.loading = true
      const params = {
        current: this.currentPage,
        size: this.pageSize,
        roleName: this.searchName
      }
      rolePage(params).then(res => {
        this.tableData = res.data.data.records
      }).catch(err => {
        this.$message.error(err.message)
      }).finally(() => {
        this.loading = false
      })
    },
    // 新增角色
    handleAdd() {
      this.status = 'add'
      this.dialogVisible = true
    },
    // 编辑角色
    handleEdit(params) {
      this.status = 'edit'
      this.addFormData.roleName = params.roleName
      this.addFormData.roleCode = params.roleCode
      this.addFormData.roleDesc = params.roleDesc
      this.addFormData.roleId = params.roleId
      this.dialogVisible = true
    },
    // 删除角色
    handleDelete(id) {
      this.$confirm('组织删除后不可恢复，请谨慎操作?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delObj(id).then(res => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.queryList()
        }).catch(err => {
          this.$message.error(err.message)
        })
      })
    },
    // 每页条数改变时触发
    handleSizeChange(val) {
      this.pageSize = val
      this.queryList()
    },
    // 当前页变时触发
    handleCurrentChange(val) {
      this.currentPage = val
      this.queryList()
    },
    // 新增/编辑角色
    onsubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          const params = {
            ...this.addFormData,
            dsType: 0
          }
          if (this.status === 'add') {
            addObj(params).then(res => {
              this.queryList()
            }).catch(err => {
              this.$message.error(err.message)
            })
          } else {
            putObj(params).then(res => {
              this.queryList()
            }).catch(err => {
              this.$message.error(err.message)
            })
          }
          this.dialogVisible = false
          this.addFormData.name = ''
          this.$refs['form'].resetFields()
        } else {
          return false
        }
      })
    },
    // 关闭新增/编辑弹窗
    handleClose() {
      this.dialogVisible = false
      this.addFormData.name = ''
      this.$refs['form'].resetFields()
    },

    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    handlePermission(row) {
      fetchRoleTree(row.roleId)
        .then(response => {
          this.checkedKeys = response.data.data
          return fetchMenuTree()
        })
        .then(response => {
          this.treeData = response.data.data
          // 解析出所有的太监节点
          this.checkedKeys = this.resolveAllEunuchNodeId(this.treeData, this.checkedKeys, [])
          this.dialogPermissionVisible = true
          this.roleId = row.roleId
          this.roleCode = row.roleCode
        })
    },
    /**
     * 解析出所有的太监节点id
     * @param json 待解析的json串
     * @param idArr 原始节点数组
     * @param temp 临时存放节点id的数组
     * @return 太监节点id数组
     */
    resolveAllEunuchNodeId(json, idArr, temp) {
      for (let i = 0; i < json.length; i++) {
        const item = json[i]
        // 存在子节点，递归遍历;不存在子节点，将json的id添加到临时数组中
        if (item.children && item.children.length !== 0) {
          this.resolveAllEunuchNodeId(item.children, idArr, temp)
        } else {
          temp.push(idArr.filter(id => id === item.id))
        }
      }
      return temp
    },
    updatePermession() {
      this.menuIds = ''
      this.menuIds = this.$refs.menuTree.getCheckedKeys().join(',').concat(',').concat(this.$refs.menuTree.getHalfCheckedKeys().join(','))
      permissionRoleMenu(this.roleCode, this.menuIds).then(() => {
        this.dialogPermissionVisible = false
        this.$notify.success('修改成功')
      })
    },
    // 权限取消
    cancal() {
      this.dialogPermissionVisible = false
    }
  }
}
</script>

<style lang="scss" scoped>
.role-list {
  height: 100%;

  .title {
    font-size: 18px;
    font-weight: 600;
    color: #252525;
    margin-bottom: 21px;
  }

  .search-icon {
    cursor: pointer;
  }

  .button-container {
    float: right;
  }
}

::v-deep .menu-dialog .el-dialog__body {
  height: 550px;
  overflow: hidden;
  overflow-y: auto;
}

.iconfont {
  margin-left: 2px;
  cursor: pointer;
}

.status-group {
  padding: 0 12px;

  .status-checkbox {
    display: block;
    height: 40px;
    line-height: 40px;
  }
}

.status-btn-box {
  text-align: center;
  border-top: 1px solid #E5E6E9;
  margin-top: 10px;

  .btn {
    margin-top: 10px;
  }
}

::v-deep .el-table__fixed-right-patch {
  background: #F5F6F7;
}
</style>
<style>
.custom-popover {
  min-width: 127px !important;
  padding: 12px 0;
}
</style>
